package com.qf.java2201.edu.userservice.security;

import cn.hutool.core.util.StrUtil;
import com.qf.java2201.edu.userservice.pojo.User;
import com.qf.java2201.edu.userservice.service.PermissionService;
import com.qf.java2201.edu.userservice.service.RoleService;
import com.qf.java2201.edu.userservice.service.UserService;
import com.qf.java2201.edu.userservice.web.model.LoginUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @date 2022/6/5
 * @desc
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        if (StrUtil.isEmpty(username)) {
            throw new RuntimeException("用户名不能为空!");
        }

        User user = userService.findUserByUserName(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户不存在!");
        }

        List<SimpleGrantedAuthority> authorities = getUserAuthorities(user.getUserId());
        return new LoginUser(user.getUserId().longValue(), user.getUsername(), user.getPassword(), authorities);
    }


    /**
     * 根据用户ID查询菜单和角色权限
     * @param userId
     * @return
     */
    public List<SimpleGrantedAuthority> getUserAuthorities(Long userId) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //获取用户菜单权限

        Set<String> menuPerms = permissionService.getMenuPermsByUserId(userId);
        if (menuPerms.size() > 0) {
            for (String perm : menuPerms) {
                if (StringUtils.hasLength(perm)) {
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perm);
                    authorities.add(authority);
                }
            }
        }
        //获取用户角色权限
        Set<String> rolePerms = roleService.getRolePermsByUserId(userId);
        if (rolePerms.size() > 0) {
            for (String perm : rolePerms) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + perm);
                authorities.add(authority);
            }
        }
        return authorities;
    }
}
